Text Justification

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ‘ ‘ when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,

words: ["This", "is", "an", "example", "of", "text", "justification."]

L: 16.

Return the formatted lines as:

  1. [
  2. "This is an",
  3. "example of text",
  4. "justification. "
  5. ]

Note: Each word is guaranteed not to exceed L in length.

Solution:

  1. public class Solution {
  2. public List<String> fullJustify(String[] words, int maxWidth) {
  3. List<String> res = new ArrayList<>();
  4. int n = words.length, i = 0;
  5. while (i < n) {
  6. int j = i, len = -1;
  7. while (j < n && len + words[j].length() + 1 <= maxWidth) {
  8. len += words[j].length() + 1;
  9. j++;
  10. }
  11. int space = 1, extra = 0;
  12. if (j != i + 1 && j != n) {
  13. space = (maxWidth - len) / (j - i - 1) + 1;
  14. extra = (maxWidth - len) % (j - i - 1);
  15. }
  16. StringBuilder sb = new StringBuilder();
  17. sb.append(words[i]);
  18. for (int k = i + 1; k < j; k++) {
  19. for (int s = space; s > 0; s--) {
  20. sb.append(' ');
  21. }
  22. if (extra-- > 0) {
  23. sb.append(' ');
  24. }
  25. sb.append(words[k]);
  26. }
  27. int left = maxWidth - sb.length();
  28. while (left-- > 0) {
  29. sb.append(' ');
  30. }
  31. res.add(sb.toString());
  32. i = j;
  33. }
  34. return res;
  35. }
  36. }